package com.promise.jokerdream.work.team.sect

import com.promise.jokerdream.database.entity.SectGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 门派工作
class SectWork(
    private val config: SectGameConfigEntity,
    uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override val name: String
        get() = "门派"

    override suspend fun executeWork(): WorkResult {
        // 1. 查询门派上香情况
        val queryIncenseResult = gameApi.querySectIncense()
        queryIncenseResult.fold(
            onSuccess = { response ->
                // 免费上香
                if (response.leftFreeFumigateTimes > 0) {
                    val freeIncenseResult = gameApi.sectFumigate("free")
                    freeIncenseResult.fold(
                        onSuccess = { incenseResponse ->
                            historyManager.addHistory(name, incenseResponse.getDescription())
                        },
                        onFailure = { exception ->
                            historyManager.addHistory(name, exception.message)
                        }
                    )
                }

                // 付费上香
                if (response.leftPaidFumigateTimes > 0 && config.paidIncenseEnabled) {
                    val paidIncenseResult = gameApi.sectFumigate("paid")
                    paidIncenseResult.fold(
                        onSuccess = { incenseResponse ->
                            historyManager.addHistory(name, incenseResponse.getDescription())
                        },
                        onFailure = { exception ->
                            historyManager.addHistory(name, exception.message)
                        }
                    )
                }
            },
            onFailure = { exception ->
                historyManager.addHistory(name, exception.message)
            }
        )

        // 2. 查询门派训练情况
        val queryTrainingResult = gameApi.querySectTraining()
        queryTrainingResult.fold(
            onSuccess = { response ->
                // 打木桩
                if (response.npcChallengedTimes < 1) {
                    val trainNpcResult = gameApi.sectTrainWithNpc()
                    trainNpcResult.fold(
                        onSuccess = { trainResponse ->
                            historyManager.addHistory(name, trainResponse.getDescription())
                        },
                        onFailure = { exception ->
                            historyManager.addHistory(name, exception.message)
                        }
                    )
                }

                // 同门切磋
                val remainingMemberTimes = 2 - response.memberChallengedTimes
                if (remainingMemberTimes > 0) {
                    // 第一次免费，第二次根据配置决定是否付费
                    val freeTimes = remainingMemberTimes - 1
                    val paidTimes = if (remainingMemberTimes > 1 && config.paidMemberTrainingEnabled) 1 else 0
                    
                    // 执行切磋
                    repeat(freeTimes + paidTimes) { index ->
                        val trainMemberResult = gameApi.sectTrainWithMember()
                        trainMemberResult.fold(
                            onSuccess = { trainResponse ->
                                historyManager.addHistory(name, trainResponse.getDescription())
                            },
                            onFailure = { exception ->
                                historyManager.addHistory(name, exception.message)
                            }
                        )
                    }
                }
            },
            onFailure = { exception ->
                historyManager.addHistory(name, exception.message)
            }
        )

        // 5. 切磋掌门（rank=1, pos=1）
        val trainMasterResult = gameApi.sectTrainWithCouncil(1, 1)
        trainMasterResult.fold(
            onSuccess = { response ->
                historyManager.addHistory(name, response.getDescription())
            },
            onFailure = { exception ->
                historyManager.addHistory(name, exception.message)
            }
        )

        // 6. 切磋首座（rank=2, pos=1-2）
        for (i in 1..2) {
            val trainElderResult = gameApi.sectTrainWithCouncil(2, i)
            trainElderResult.fold(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, exception.message)
                }
            )
        }

        // 7. 切磋堂主（rank=3, pos=1-4）
        for (i in 1..4) {
            val trainHallMasterResult = gameApi.sectTrainWithCouncil(3, i)
            trainHallMasterResult.fold(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, exception.message)
                }
            )
        }

        // 8. 查询门派任务并领取奖励
        val queryTaskResult = gameApi.querySectTask()
        queryTaskResult.fold(
            onSuccess = { response ->
                // 遍历任务列表，领取已完成的任务奖励（state == 1）
                response.task.forEach { task ->
                    if (task.state == 1) {
                        val rewardResult = gameApi.getSectTaskReward(task.id)
                        rewardResult.fold(
                            onSuccess = { rewardResponse ->
                                historyManager.addHistory(name, rewardResponse.getDescription())
                            },
                            onFailure = { exception ->
                                historyManager.addHistory(name, exception.message)
                            }
                        )
                    }
                }
            },
            onFailure = { exception ->
                historyManager.addHistory(name, exception.message)
            }
        )

        return WorkResult.Success
    }
}